<template>
  <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="600px"
      class="OtherCostForm"
      :before-close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="OtherCostForm-form">
      <el-form-item label="成本名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入成本名称" maxlength="50" show-word-limit/>
      </el-form-item>
      <el-form-item label="费用(¥)" prop="cost">
        <el-input-number v-model="form.cost" :min="0" :step="1" :precision="2" class="OtherCostForm-form-number" />
      </el-form-item>
      <el-form-item label="日期" prop="date">
        <el-date-picker v-model="form.date" type="date" placeholder="选择日期" class="OtherCostForm-form-input"/>
      </el-form-item>
      <el-form-item label="备注" prop="note">
        <el-input v-model="form.note" type="textarea" :rows="3" placeholder="可填写备注，最多100字符" maxlength="100"
                  show-word-limit/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="OtherCostForm-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import {ref, reactive, watch} from 'vue'

const props = defineProps({
  visible: {type: Boolean, default: false},
  title: {type: String, default: '新增其他成本'},
  initial: {type: Object, default: null}
})
const emits = defineEmits(['update:visible', 'confirm'])

const dialogVisible = ref(false)
const formRef = ref()
const form = reactive({ name: '', cost: 0, date: '', note: '' })

const rules = reactive({
  name: [{ required: true, message: '请输入成本名称', trigger: 'blur' }],
  cost: [
    { required: true, message: '请输入费用', trigger: 'change' },
    { validator: (_r,v,cb)=> { const str = String(v); if(v===''||v===null) return cb(new Error('请输入费用')); if(Number(v) < 0) return cb(new Error('费用不能小于0')); if(!/^\d+(?:\.\d{1,2})?$/.test(str)) return cb(new Error('最多保留两位小数')); cb() }, trigger: 'change' }
  ],
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  note: [{ validator: (_r,v,cb)=> { if(v && v.length>100) return cb(new Error('备注最多100字符')); cb() }, trigger: 'blur' }]
})

watch(() => props.visible, v => { dialogVisible.value = v; if (v) init() })
watch(dialogVisible, v => { if (!v) emits('update:visible', false) })

const today = () => { const d = new Date(); return new Date(d.getFullYear(), d.getMonth(), d.getDate()) }
const formatDate = (d) => { if (!d) return ''; const dt = new Date(d); const y=dt.getFullYear(); const m=String(dt.getMonth()+1).padStart(2,'0'); const dd=String(dt.getDate()).padStart(2,'0'); return `${y}-${m}-${dd}` }

const init = () => {
  if (props.initial) {
    form.name = props.initial.name || ''
    form.cost = props.initial.cost != null ? Number(props.initial.cost) : 0
    const d = props.initial.date || props.initial.costDate
    form.date = d ? new Date(d) : today()
    form.note = props.initial.note || ''
  } else {
    form.name = ''
    form.cost = 0
    form.date = today()
    form.note = ''
  }
}

const handleClose = () => { dialogVisible.value = false }
const handleConfirm = async () => {
  try {
    await formRef.value?.validate()
    emits('confirm', {
      id: props.initial && props.initial.id != null ? props.initial.id : undefined,
      name: form.name.trim(),
      cost: Number(form.cost),
      date: formatDate(form.date),
      note: form.note?.trim() || ''
    })
    handleClose()
  } catch (_) { /* ignore */ }
}
</script>
<style scoped lang="scss">
.OtherCostForm {
  &-form { padding: 8px 0; }
  &-form-number { width: 220px; }
  &-form-input { width: 220px; }
  &-footer { display: flex; justify-content: flex-end; gap: 8px; }
}
</style>
